//
// Created by Mzoro on 2022/4/22.
//

#include "includes/includes.h"
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

Node *lookup(char *key);

Node *table[TABLE_LENGTH];

char *get(char *key) {
    Node *n = lookup(key);
    if (n != NULL) {
        return n->value;
    }else{
        return NULL;
    }
}

Node *lookup(char *key) {
    unsigned h = hash(key);
    Node *n = table[h];
    if (n == NULL) {
        return NULL;
    } else {
        while (strcmp(n->key, key) != 0 && (n = n->next) != NULL) {
        }
        return n;
    }
}

void put(char *key, char *value) {
    Node *n;
    if ((n = lookup(key)) != NULL) {
        //表里存在，那么替换值
        free(n->value);
        n->value = cpword(value);
    } else {
        // 表里不存在
        n = mapalloc();
        n->key = cpword(key);
        n->value = cpword(value);
        n->next = NULL;
        table[hash(key)] = n;
    }
}

Node *mapalloc() {
    return (Node *) malloc(sizeof(struct node));
}

char *cpword(char *word) {
    char *tmp = malloc((strlen(word)) + 1);
    strcpy(tmp, word);
    return tmp;
}

unsigned hash(const char *key) {
    unsigned h = 0;
    for (; *key!='\0' ; key++) {
        h = *key + h * 31;
    }
    return h % TABLE_LENGTH;
}
